<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="用户名" prop="Member_Name">
      <el-input v-model="ruleForm.Member_Name" />
    </el-form-item>

       <el-form-item label="密码" prop="Member_Pwd">
      <el-input type="password" v-model="ruleForm.Member_Pwd" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        登录
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import axios from 'axios'
import type { FormInstance, FormRules } from 'element-plus'
import {ElMessage} from 'element-plus'
import {useUserStore} from '../stores/user.ts'
import {useRouter} from 'vue-router'

//创建仓库实例
const userStore = useUserStore();

//创建路由实例
const router = useRouter();

const ruleFormRef = ref<FormInstance>()

const ruleForm = reactive({
  Member_Name: '',
  Member_Pwd: ''
})

//规则验证
const rules = reactive<FormRules>({
  Member_Name: [
    { required: true, message: '用户名称不能为空', trigger: 'blur' },
    {pattern:/^[A-Za-z]+$/,message: '用户名称只能为字母',trigger: 'blur'}
  ],
    Member_Pwd: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 3, max: 10, message: '密码长度需介于3-10位之间', trigger: 'blur' },
  ]
})

//提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      
      axios.post('/api/Members/MemberLogin?userName='+ruleForm.Member_Name+'&userPwd='+ruleForm.Member_Pwd
      )
      .then(res=>{
        console.log(res.data.data);
        //判断结果
        if(res.data.data.login_Code==1)
        {
            ElMessage.success(res.data.data.login_Message);

            //将用户信息保存到仓库中
            userStore.uName=res.data.data.login_Data.member_Name;
            userStore.isLogin=true;

            //将Token信息保存到本地
            window.localStorage.setItem("token",res.data.data.login_JWT);


            //将JWT生成的Token 传入每一次请求的请求头(Headers)中
            axios.defaults.headers.common['Authorization'] = 'Bearer ' + res.data.data.login_JWT;

            //跳转到首页
            router.push('/Home');
        }
        else{
          ElMessage.error(res.data.data.login_Message);
        }
      })

    } else {
      console.log('error submit!', fields)
    }
  })
}

//重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

</script>
